/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * CategoriasEdit.java
 *
 * Created on 15/06/2011, 00:04:12
 */
package pacote;

import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.TypedQuery;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Pardall
 */
public class CategoriasEdit extends javax.swing.JFrame {

    private EntityManager em;
    private List<Categorias> cat;
    private List<Integer> updated;
    private boolean ignoreTableChanges;
    DefaultTableModel categorias;

    /** Creates new form CategoriasEdit */
    public CategoriasEdit(EntityManager exm) {
        initComponents();
        em = exm;
        ignoreTableChanges = false;
        updated = new ArrayList<Integer>();
        cat = getCat();
        categorias = (DefaultTableModel) jTable1.getModel();
        fillTable();

        jTable1.getModel().addTableModelListener(new TableModelListener() {

            public void tableChanged(TableModelEvent e) {
                if (!ignoreTableChanges) {
                    if (e.getColumn() != 0) {
                        int row = e.getFirstRow();
                        updated.add(row);
                        cat.get(row).setNome((String)categorias.getValueAt(row, 1));
                        cat.get(row).setDescr((String)categorias.getValueAt(row, 2));
                        save.setEnabled(true);
                    }
                }
            }
        });
    }

    private void fillTable() {
        ignoreTableChanges = true;
        Object[] row = new Object[3];
        row[0] = false;
        categorias.setRowCount(0);
        for (Categorias c : cat) {
            row[1] = c.getNome();
            row[2] = c.getDescr();
            categorias.addRow(row);
        }
        ignoreTableChanges = false;
    }

    private List<Categorias> getCat() {
        TypedQuery<Categorias> query = em.createNamedQuery("Categorias.findAll", Categorias.class);
        return query.getResultList();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        add = new javax.swing.JButton();
        rem = new javax.swing.JButton();
        save = new javax.swing.JButton();
        refresh = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "", "Nome", "Descrição"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Boolean.class, java.lang.Object.class, java.lang.Object.class
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }
        });
        jTable1.setColumnSelectionAllowed(true);
        jTable1.getTableHeader().setReorderingAllowed(false);
        jScrollPane1.setViewportView(jTable1);
        jTable1.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jTable1.getColumnModel().getColumn(0).setPreferredWidth(5);
        jTable1.getColumnModel().getColumn(1).setPreferredWidth(40);

        add.setText("Adicionar");
        add.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addActionPerformed(evt);
            }
        });

        rem.setText("Excluir");
        rem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                remActionPerformed(evt);
            }
        });

        save.setText("Salvar");
        save.setEnabled(false);
        save.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveActionPerformed(evt);
            }
        });

        refresh.setText("Atualizar");
        refresh.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                refreshActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 375, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(save, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(refresh, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(rem, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(add, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(add)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(rem)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(refresh)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(save))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 275, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void addActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addActionPerformed
        if (evt.getSource() == this.add) {
            cat.add(new Categorias());
            Object[] row = new Object[3];
            row[0] = false;
            row[1] = "Nome";
            row[2] = "Descr";
            categorias.addRow(row);
        }
    }//GEN-LAST:event_addActionPerformed

    private void saveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveActionPerformed
        if (evt.getSource() == this.save) {
            Categorias c = new Categorias();
            em.getTransaction().begin();
            for (int i : updated) {
                if (cat.get(i).getId() != null) {
                    c = em.find(Categorias.class, cat.get(i).getId());
                    c.setNome(cat.get(i).getNome());
                    c.setDescr(cat.get(i).getDescr());
                } else {
                    em.persist(cat.get(i));
                }
            }
            em.getTransaction().commit();
            save.setEnabled(false);
        }
    }//GEN-LAST:event_saveActionPerformed

    private void remActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_remActionPerformed
        if (evt.getSource() == this.rem) {
            Categorias c = new Categorias();
            em.getTransaction().begin();
            for (int i = 0; i < categorias.getRowCount(); i++) {
                if ((Boolean) categorias.getValueAt(i, 0) == true) {
                    c = em.find(Categorias.class, cat.get(i).getId());
                    em.remove(c);
                }
            }
            em.getTransaction().commit();
            cat = getCat();
            updated.clear();
            fillTable();
        }
    }//GEN-LAST:event_remActionPerformed

    private void refreshActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_refreshActionPerformed
        if (evt.getSource() == this.refresh){
            cat = getCat();
            fillTable();
        }
    }//GEN-LAST:event_refreshActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton add;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JButton refresh;
    private javax.swing.JButton rem;
    private javax.swing.JButton save;
    // End of variables declaration//GEN-END:variables
}
